<template>
  <el-card class="box-card" header="管理员管理">
    <DataManageTable
      ref="tableRef"
      :tableConfig="tableConfig"
      @getTableData="getTableData"
      @saveRowEvent="saveRowEvent"
    />
  </el-card>
</template>

<script setup>
import { getDataByIdAsync } from '@/api/systemManage/adminRole'
import {
  addUserRoleAsync,
  removeUserRoleAsync,
  getTableDataAsync,
  saveOrUpdateAsync
} from '@/api/systemManage/adminUser'
import { useDataManage } from '@/hooks'
import tableConfig from './config/table.config'

// 表格实例
const tableRef = ref(null)
// 数据表格
const { getTableData, saveRowEvent } = useDataManage({
  saveParamsCallBack,
  tableRef,
  async getTableDataAsync() {
    // 获取表格数据
    const res = await getTableDataAsync()
    // 设置角色列表
    res.data.records.forEach((record) => {
      record.roleIds = record.roleList.map((role) => role.id)
    })
    return res
  },
  async saveOrUpdateAsync(params) {
    // 新增状态
    const { roleIds, isNew, ...restParams } = params
    // 新增管理员用户
    if (isNew) {
      return saveOrUpdateAsync(restParams)
    }
    // 获取之前角色列表
    const { data: oldRoleList } = await getDataByIdAsync({ adminId: restParams.id })
    // 旧角色id列表
    const oldRoleIds = oldRoleList.map((role) => role.id)
    // 新增角色id列表
    const addRoleIds = roleIds.filter((id) => !oldRoleIds.includes(id))
    // 移除角色id列表
    const removeRoleIds = oldRoleIds.filter((id) => !roleIds.includes(id))
    // 新增管理员用户角色
    addRoleIds?.length && (await addUserRoleAsync({ adminId: restParams.id, roleIds: addRoleIds }))
    // 移除管理员用户角色
    removeRoleIds?.length &&
      (await removeUserRoleAsync({ adminId: restParams.id, roleIds: removeRoleIds }))
    // 修改管理员用户
    return saveOrUpdateAsync(restParams)
  }
})

/**
 * @description 保存参数回调
 * @typedef {{
 * id?: string,
 * nickName: string,
 * username: string,
 * password: string,
 * roleIds: number[],
 * }} RowData
 * @param {RowData[]} updateRow
 * @param {RowData} row
 */
function saveParamsCallBack(updateRow, row) {
  // 当前行
  const currentRow = updateRow[0] || row
  // 参数信息
  const { id, nickName, username, newPassword, roleIds } = currentRow
  // 新增
  if (!('id' in currentRow)) {
    return {
      nickName,
      username,
      password: newPassword || undefined,
      isNew: true
    }
  }
  // 修改
  return {
    id,
    nickName,
    username,
    password: newPassword || undefined,
    roleIds: roleIds || [],
    isNew: false
  }
}
</script>

<style scoped lang="scss">
.box-card {
  height: 100%;

  :deep(.el-card__body) {
    height: calc(100% - 58px);
  }
}
</style>
